package com.example.administrator.text;

import android.annotation.TargetApi;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.UploadDialog;

/**
 * 意见反馈
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FeedbackActivity extends BaseActivity implements View.OnLayoutChangeListener{
    private String mString,mValue;
    private UploadDialog mUploadDialog;
    private int mKeyHeight = 0;  //软件盘弹起后所占高度阀值

    @Bind(R.id.edit_feedbck)       EditText mEditText;  //输入框
    @Bind(R.id.text_feedbck_hint)  TextView mTextViewHint;
    @Bind(R.id.tv_feedb)           TextView mTextViewFeedb;
    @Bind(R.id.feedback_frame)     FrameLayout mFrameLayout;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);

        ButterKnife.bind(this);
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        initEditText();
        init();

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void init() {

        int screenHeight = getInformation.getNewGetInformation(this).getIHeight(this);
        mKeyHeight = screenHeight/3;
        View activityRootView = findViewById(R.id.root_layout);
        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_feedbck);
        activityRootView.addOnLayoutChangeListener(this);
        controlKeyboardLayout(activityRootView,frameLayout);
        String feedb = getString(R.string.app_name)+getInformation.getNewGetInformation(this).getVersion()+"版意见反馈";
        mTextViewFeedb.setText(feedb);
    }

    /**
     * 返回
     */
    @OnClick(R.id.image_feedbck) void aboutReturn(){
        finish();
    }

    /**
     * 提交
     */
    @OnClick(R.id.text_feedbck) void feedbck(){
        mString = mEditText.getText().toString().trim();
        Log.e("mString", mString);
        if(NetUtils.getInstance(this).checkNetWork()){

            if(!mString.equals("")){
                getFeedbckStringData();

            }else {super.getToast("提交的内容不能为空");}

        }else {super.getToast(getString(R.string.no_network));}

    }

    /**
     * @param root 最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override public void onGlobalLayout() {
                Rect rect = new Rect();
                root.scrollTo(0, 0);
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                    scrollToView.setPadding(0,0,0,rootInvisibleHeight+10);

                } else {
                    //键盘隐藏
                    scrollToView.setPadding(0,0,0,10);
                }
            }
        });
    }

    /**
     * 提交的请求
     */
    private void getFeedbckStringData(){
        String url = "";
        mUploadDialog = new UploadDialog(this,"提交中");
        mUploadDialog.show();
        String id = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
        LogUtil.eE("",id);
        String token = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        try {
            mValue = URLDecoder.decode(mString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mMap = new HashMap<>();
        mMap.put("userid",id);
        mMap.put("feedbackContent",mString);
        mMap.put("ver", getInformation.getNewGetInformation(this).getVersion());
        mMap.put("vertype",1);
        if(getString(R.string.app_name).equals("牛郎WiFi")){
            mMap.put("appType",2);
        }else if(getString(R.string.app_name).equals("NewFi")){
            mMap.put("appType",1);
        }
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngMycenter_saveFeedback,stringJson,token,id,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,token,id,Url.mStirngMycenter_saveFeedback,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        LogUtil.eE("fwq","  "+url);
        getLogger().info("getFeedbckStringData()--->已经反馈--fwq"+url+"stringJson"+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    getLogger().info("getFeedbckStringData()--->onSuccess--String"+response);
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    LogUtil.eE("",response);
                    mUploadDialog.dismiss();
                    if (code.equals("1")) {
                        finish();
                        Toast.makeText(FeedbackActivity.this, "提交成功", Toast.LENGTH_SHORT).show();

                    } else if (code.equals("-2")) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(FeedbackActivity.this);
                        crowdRetunDialog.show();
                    } else {
                        Toast.makeText(FeedbackActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {e.printStackTrace();}

            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(FeedbackActivity.this, error.toString());
            }
        });
    }

    private void initEditText(){
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                int hint = s.toString().length();
                mTextViewHint.setText("" + hint);
            }

            @Override public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override protected void onDestroy() {
        super.onDestroy();

        if(mMap !=null){mMap.clear();}

        if(mUploadDialog !=null){mUploadDialog.dismiss();}
    }

    @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起

         Log.e("makeText","            "+(oldBottom - bottom));
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > mKeyHeight)){

            Toast.makeText(FeedbackActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();

        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > mKeyHeight)){

            Toast.makeText(FeedbackActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();

        }


    }
}
